package com.innovation.chengzhangriji.ui;

import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.http.Client;
import com.loopj.android.http.FileAsyncHttpResponseHandler;

import org.apache.http.Header;

import java.io.File;

public class DiscoverVideoActivity extends BaseActivity implements MediaPlayer.OnCompletionListener {

    private String videoUrl;

    private VideoView video;

    private ImageView btnPlay;

    private TextView textProgress;

    private int heightTop;

    private int heightBottom;

    private boolean complete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        videoUrl = getIntent().getStringExtra("videoUrl");
        int start = videoUrl.indexOf(Config.VIDEO);
        String subUrl = videoUrl.substring(start);

        setContentView(R.layout.activity_discover_video);
        video = (VideoView) findViewById(R.id.video);
        video.setOnCompletionListener(this);
        btnPlay = (ImageView) findViewById(R.id.btn_play);
        textProgress = (TextView) findViewById(R.id.text_progress);

        FrameLayout layoutTop = (FrameLayout) findViewById(R.id.layout_top);
        FrameLayout layoutBottom = (FrameLayout) findViewById(R.id.layout_bottom);
        DisplayMetrics dm = getResources().getDisplayMetrics();

        int w = dm.widthPixels;
        int h = (int) ((dm.heightPixels - 240 * dm.density) / 2);

        heightTop = h;
        heightBottom = dm.heightPixels - h;

        RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(w, h);
        lp1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        layoutTop.setLayoutParams(lp1);

        RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(w, h);
        lp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutBottom.setLayoutParams(lp2);

        // 因为负载均衡,资源的前缀地址会变化.保存hashcode时,只保存从resource开始的部分.
        File file = new File(getExternalCacheDir(), String.valueOf(subUrl.hashCode()));
        if (!file.exists()) {
            downloadVideo(file);
        } else {
            complete = true;
            textProgress.setVisibility(View.INVISIBLE);
            playVideo(file);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        video.stopPlayback();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float y = event.getY();
        // 判断点击的位置
        if (y <= heightTop || y >= heightBottom) {
            finish();
        } else {
            // 判断视频是否正在播放
            if (!video.isPlaying() && complete) {
                btnPlay.setVisibility(View.INVISIBLE);
                video.start();
            }
        }
        return true;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        btnPlay.setVisibility(View.VISIBLE);
    }

    private void downloadVideo(File file) {
        Client.downloadFile(this, videoUrl, new FileAsyncHttpResponseHandler(file) {
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
                textProgress.setTextColor(Color.parseColor("#ff3745"));
                textProgress.setTextSize(20);
                textProgress.setText(getString(R.string.tip_video_download_failed));
//                textProgress.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {
                textProgress.setTextColor(Color.WHITE);
                textProgress.setTextSize(10);
                int progress = (int) (bytesWritten * 1.0f / totalSize * 100);
                textProgress.setText(progress + "%");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, File file) {
                complete = true;
                textProgress.setVisibility(View.INVISIBLE);
                playVideo(file);
            }

        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                textProgress.setTextColor(Color.parseColor("#ff3745"));
                textProgress.setTextSize(20);
                textProgress.setText(getString(R.string.tip_video_download_failed));
            }
        });
    }

    private void playVideo(File file) {
        video.setVideoPath(file.getPath());
        video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                video.setBackgroundColor(Color.TRANSPARENT);
            }
        });
        video.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(complete && video.isPlaying() && video.canPause()) {
            video.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(complete) {
            video.start();
        }
    }

}
